package com.zhang.dao.impl;


import com.zhang.dao.UserDao;
import com.zhang.pojo.User;
import com.zhang.utils.JDBCUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class UserDaoImpl implements UserDao {
    private JdbcTemplate jdbcTemplate = new JdbcTemplate(JDBCUtils.getDataSource());


    @Override
    public long save(User user) {
        String sql = "INSERT INTO `userpro`.`user` (`id`, `username`,  `password`, `email`, `sex`)  VALUES(?, ?, ?, ?, ? )  ";

        //创建PreparedStatementCreator
        PreparedStatementCreator creator = new PreparedStatementCreator() {
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                //使用原始jdbc完成有个PreparedStatement的组建
                PreparedStatement preparedStatement = connection.prepareStatement(sql, PreparedStatement.RETURN_GENERATED_KEYS);
                preparedStatement.setObject(1,null);
                preparedStatement.setString(2,user.getUsername());
                preparedStatement.setString(3,user.getPassword());
                preparedStatement.setString(4,user.getEmail());
                preparedStatement.setString(5,user.getSex());
                return preparedStatement;
            }
        };
        //创建keyHolder
        GeneratedKeyHolder keyHolder = new GeneratedKeyHolder();
        jdbcTemplate.update(creator,keyHolder);
        //获得生成的主键
        long userId = keyHolder.getKey().longValue();
        return userId; //返回当前保存用户的id 该id是数据库自动生成的

    }


    @Override
    public void saveUserLove(long userId, int loveId) {
        String sql = "INSERT INTO `userpro`.`user_love` (`userID`, `loveId`) VALUES (?, ?)";
        jdbcTemplate.update(sql,userId,loveId);
    }

    @Override
    public User login(String username, String password) {
        String sql = "SELECT * FROM `user` WHERE `username`= ? AND `password`=?";
        try {
           return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), username, password);
        } catch (DataAccessException e) {
            return null;
        }

    }

    @Override
    public User findUser(int userId) {
        String sql = "SELECT * FROM `user` WHERE id = ?";
        try {
            return jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<User>(User.class), userId);
        } catch (DataAccessException e) {
            return null;
        }
    }
}
